<?php

namespace Xx2025\Kingdee\Erp;

use GuzzleHttp\Client as Guzzle;
use Xx2025\Kingdee\Erp\Response\GyErpTradeAdd;

class Client{


    private static  $_config;
    private static  $timeout = 30;

    public static $guzzleHttp = null;


    public static function init($apiUrl, $appKey, $sessionKey, $secret)
    {
        if(empty(self::$_config)){
            self::$_config = [
                'apiUrl' => $apiUrl,
                'appKey' => $appKey,
                'sessionKey' => $sessionKey,
                'secret' => $secret,
            ];
        }
    }

    public static function getGuzzleHttp()
    {
        if(empty(self::$guzzleHttp)){
            self::$guzzleHttp = new Guzzle();
        }
        return clone self::$guzzleHttp;
    }








    public static function request($method, $requestBody, $erpResponse = null)
    {
        $config = self::$_config;

        $requestBody['appkey'] = $config['appKey'];
        $requestBody['sessionkey'] = $config['sessionKey'];
        $requestBody['method'] = $method;

        $requestBodyStr = json_encode($requestBody, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $str = $config['secret'] . $requestBodyStr . $config['secret'];
        $sign = strtoupper(md5($str));

        $requestBody['sign'] = $sign;


        try{

            $guzzleClient = self::getGuzzleHttp();
            $response = $guzzleClient->post($config['apiUrl'], [
                'json' => $requestBody,
                'timeout' => self::$timeout,
            ]);

            $body = $response->getBody()->getContents();
            $data = json_decode($body, true);

            $successful = $data['success'] ?? false;

            if(empty($erpResponse)){
                $erpResponse = BaseResponse::getBaseResponseInstance();
            }




            $erpResponse->setStatusCode($response->getStatusCode());
            $erpResponse->setSuccessful($successful);

            if(!$successful){
                $erpResponse->setErrMsg($data['errorDesc'] ?? '');
            }

            $erpResponse->setRequestContents($requestBody);
            $erpResponse->setResponseContents($data);

            return $erpResponse;

        }catch (\Throwable $exception){
               throw $exception;
        }
    }
}